package kku.cs.util;

import java.sql.Date;
import java.sql.Time;

public class Converter {

	static public boolean ObjToBoolean(Object o) {
		if (o instanceof Boolean)
			return ((Boolean) o).booleanValue();
		else if (o instanceof Integer) {
			return ((Integer) o).intValue() != 0;
		} else if (o instanceof Short) {
			return ((Short) o).shortValue() != 0;
		} else {
			String v = o.toString();
			if (v.equalsIgnoreCase("True") || v.equalsIgnoreCase("T")
					|| v.equalsIgnoreCase("1") || v.equalsIgnoreCase("Y")
					|| v.equalsIgnoreCase("Yes")) {
				return true;
			}
		}
		return false;
	}

	static public Date ObjToDate(Object o) {

		if (o == null)
			return null;
		if (o instanceof Date) {
			return (Date) o;
		}
		if (o instanceof java.util.Date) {
			return new Date(((java.util.Date) o).getTime());
		}
		if (o instanceof Number) {
			long v = ((Number) o).longValue();
			return new Date(v);
		}
		try {
			String v = o.toString().trim();
			if(v.length()<2) return null;
			return Date.valueOf(v);
		} catch (Exception e) {
			System.err.println("date error:" + o);
			e.printStackTrace();
			return null;
		}
	}

	static public Time ObjToTime(Object o) {
		if (o == null)
			return null;
		if (o instanceof Time) {
			return (Time) o;
		}
		if (o instanceof java.util.Date) {
			java.util.Date d = (java.util.Date) o;
			return new Time(d.getHours(), d.getMinutes(), d.getSeconds());
		}
		if (o instanceof Number) {
			long v = ((Number) o).longValue();
			Date d = new Date(v);
			return new Time(d.getHours(), d.getMinutes(), d.getSeconds());
		}
		String v = o.toString();
		return Time.valueOf(v);
	}

	static public double ObjToDouble(Object o) {
		if (o == null)
			return 0;
		if (o instanceof Number) {
			return ((Number) o).doubleValue();
		}
		String v = o.toString();
		return Double.parseDouble(v);
	}

	static public int ObjToInt(Object o) {
		if (o == null)
			return 0;
		if (o instanceof Number) {
			return ((Number) o).intValue();
		}
		String v = o.toString();
		if (v.length() <= 0)
			return 0;
		return Integer.parseInt(v);
	}

	static public long ObjToLong(Object o) {
		if (o == null)
			return 0;
		if (o instanceof Number) {
			return ((Number) o).longValue();
		}
		String v = o.toString();
		return Long.parseLong(v);
	}

	static public short ObjToShort(Object o) {
		if (o == null)
			return 0;
		if (o instanceof Number) {
			return ((Number) o).shortValue();
		}
		String v = o.toString();
		return Short.parseShort(v);
	}

	static public float ObjToFloat(Object o) {
		if (o == null)
			return 0;
		if (o instanceof Number) {
			return ((Number) o).floatValue();
		}
		String v = o.toString();
		return Float.parseFloat(v);
	}

	static public String delphiDate(Object o) {
		Date d = ObjToDate(o);
		return d.getDate() + "/" + (d.getMonth() + 1) + "/"
				+ (d.getYear() + 1900);
	}
}
